<template>
    <div class="container_box">
        <el-scrollbar class="main_box">
            <div class="crowd-manage-detail-main">
                <el-form ref="formRef" label-width="120px" :model="formData" :rules="rules">
                    <div class="content">
                        <el-form-item label="人群包名称" prop="name">
                            <el-input
                                v-model="formData.name"
                                placeholder="请输入人群包名称"
                                maxlength="15"
                                clearable
                                class="input_icon"
                                :disabled="formData.isDisabled"
                                show-word-limit>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="人群描述" prop="crowd_describe" class="crowd_describe">
                            <el-input
                                v-model="formData.crowd_describe"
                                type="textarea"
                                :rows="4"
                                placeholder="请输入人群包描述"
                                maxlength="150"
                                show-word-limit
                                :disabled="formData.isDisabled" />
                        </el-form-item>
                        <el-form-item label="人群设定" prop="crowd_set">
                            <el-radio-group
                                v-model="formData.crowd_set"
                                :disabled="formData.isDisabled || formData.isDisabled2"
                                @change="changeRadio">
                                <el-radio :label="1">手机号上传</el-radio>
                                <el-radio :label="2">客户筛选</el-radio>
                                <!-- <el-radio :label="3">线索筛选</el-radio> -->
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item v-if="formData.crowd_set == 1" label="">
                            <div class="mobile-upload">
                                <div class="mobile-upload-title">
                                    请下载手机号模版，按格式填写后导入<span @click="handlerDownloadTemp">下载模版</span>
                                </div>
                                <!-- <ZWUpload :upInfo="fileInfo" @submit="getFile" /> -->
                                <el-upload
                                    ref="uploadRef"
                                    class="upload-box"
                                    action="#"
                                    :auto-upload="false"
                                    :limit="1"
                                    accept=".xls,.xlsx,.csv"
                                    drag
                                    :file-list="fileList"
                                    :disabled="formData.isDisabled || formData.isDisabled2"
                                    :on-change="onHandleChange"
                                    :on-remove="onRemoveUpload">
                                    <div v-if="formData.file_name" class="file-box">
                                        <div><img class="file_img" src="/static/file/xls.png" alt="" /></div>
                                        <div class="file_name">{{ formData.file_name }}</div>
                                    </div>
                                    <el-icon v-else class="el-icon--upload"><upload-filled /></el-icon>
                                    <div class="el-upload__text">
                                        <div>拖拽文件至此区域上传支持xls、xlsx文件格式</div>
                                        <div></div>
                                        <div><el-button>点击上传</el-button></div>
                                    </div>
                                    <template #tip>
                                        <div class="el-upload__tip">
                                            识别到有效手机号 <span>{{ formData.validMobileCount }}</span
                                            >个
                                        </div>
                                    </template>
                                </el-upload>
                            </div>
                        </el-form-item>
                        <el-form-item v-if="formData.crowd_set == 2" label="">
                            <el-card shadow="nvner">
                                <el-form
                                    :model="formData.cust_screen"
                                    :disabled="formData.isDisabled"
                                    label-width="100px"
                                    class="screen-box">
                                    <el-form-item label="手机号客户">
                                        <el-radio-group v-model="formData.cust_screen.is_have_mobile">
                                            <el-radio :label="1">不限制</el-radio>
                                            <el-radio :label="2">有手机号</el-radio>
                                            <el-radio :label="3">无手机号</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                    <el-form-item label="客户阶段" class="screen-form-item">
                                        <el-select
                                            v-model="formData.cust_screen.cust_stage"
                                            filterable
                                            clearable
                                            placeholder="请选择客户阶段"
                                            size="small"
                                            @visible-change="visibleChangeCustStage">
                                            <el-option
                                                v-for="item in formData.custStageList"
                                                :key="item.id"
                                                :label="item.name"
                                                :value="item.id" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="客户来源" class="screen-form-item">
                                        <el-select
                                            v-model="formData.cust_screen.cust_source"
                                            filterable
                                            clearable
                                            placeholder="请选择客户来源"
                                            size="small"
                                            @visible-change="visibleChangeCust">
                                            <el-option
                                                v-for="item in formData.custSourceList"
                                                :key="item.id"
                                                :label="item.name"
                                                :value="item.id" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="标签" class="screen-form-item">
                                        <el-select
                                            v-model="formData.cust_screen.tag_type"
                                            placeholder="请选择标签"
                                            size="small">
                                            <el-option
                                                v-for="item in tagOptions"
                                                :key="item.code"
                                                :label="item.label"
                                                :value="item.code" />
                                        </el-select>
                                        <el-button
                                            v-if="formData.cust_screen.tag_type != 3"
                                            class="screen-form-item-btn"
                                            size="small"
                                            @click="handlerTag('1')"
                                            >选择标签</el-button
                                        >
                                        <div v-if="formData.cust_screen.tag_type != 3" class="tag-list">
                                            <span
                                                v-for="(item, index) in formData.tagList"
                                                :key="item.id"
                                                style="margin: 0 10px 10px 0">
                                                <el-tag
                                                    :key="item.id"
                                                    :closable="!(formData.isDisabled || formData.isDisabled2)"
                                                    type="warning"
                                                    @close="closeTag(index, '1')">
                                                    {{ item.name }}
                                                </el-tag>
                                            </span>
                                        </div>
                                    </el-form-item>
                                    <el-form-item label="排除标签" class="screen-form-item">
                                        <el-select
                                            v-model="formData.cust_screen.exclude_tag_type"
                                            placeholder="请选择排除标签"
                                            size="small">
                                            <el-option
                                                v-for="item in tagOptions"
                                                :key="item.code"
                                                :label="item.label"
                                                :value="item.code" />
                                        </el-select>
                                        <el-button
                                            v-if="formData.cust_screen.exclude_tag_type != 3"
                                            class="screen-form-item-btn"
                                            size="small"
                                            @click="handlerTag('2')">
                                            选择标签
                                        </el-button>
                                        <div v-if="formData.cust_screen.exclude_tag_type != 3" class="tag-list">
                                            <span
                                                v-for="(item, index) in formData.noTagList"
                                                :key="item.id"
                                                style="margin: 0 10px 10px 0">
                                                <el-tag
                                                    :key="item.id"
                                                    :closable="!(formData.isDisabled || formData.isDisabled2)"
                                                    type="warning"
                                                    @close="closeTag(index, '2')">
                                                    {{ item.name }}
                                                </el-tag>
                                            </span>
                                        </div>
                                    </el-form-item>
                                </el-form>
                            </el-card>
                            <div class="screen-desc">
                                识别到客户<span>{{ formData.validCustCount }}</span
                                >个 <span class="recalculate" @click="handlerRecalculate">重新计算</span>
                            </div>
                        </el-form-item>
                        <el-form-item label="是否锁定" prop="title">
                            <el-switch
                                v-model="formData.is_lock"
                                :disabled="formData.isDisabled || formData.crowd_set == 1"></el-switch>
                            <el-tooltip placement="right">
                                <template #content>
                                    <div style="width: 150px">
                                        未锁定：如果筛选/规则计算结果发生变化，此人群包的名单也会实时更新；
                                        <div>已锁定：如果筛选/规则计算结果发生变化，此人群包的名单不会发生变化。</div>
                                    </div>
                                </template>
                                <el-icon class="help_icon" color="#ccc"
                                    ><QuestionFilled style="width: 16px; height: 16px"
                                /></el-icon>
                            </el-tooltip>
                        </el-form-item>
                        <div class="text_box">
                            <h3 class="box_tips">注意：</h3>
                            <p>1、手机号上传的设定方式，人群包锁定，不可变更。</p>
                            <p>
                                2、客户筛选/线索筛选的设定方式，人群包可设置锁定/非锁定来选择人群包中的人群是否动态变化。
                            </p>
                        </div>
                    </div>
                </el-form>
                <BatchLabel ref="batchLabelRef" @save="getTagsFun" />
            </div>
        </el-scrollbar>
        <div class="footer_box">
            <template v-if="route.query.type === 'look'">
                <el-button type="primary" @click="backHandle"> 确定 </el-button>
            </template>
            <template v-else>
                <el-button @click="backHandle">取消</el-button>
                <el-button type="primary" @click="onSubmit">保存</el-button>
            </template>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import type { UploadFile } from 'element-plus/es/components/upload/src/upload.type';
import FooterBtn from '@/view/smartMarketing/components/FooterBtn.vue';
import ZWUpload from '@/components/ZWUpload.vue';
import BatchLabel from '@/components/BatchLabel.vue';
import {
    crowdPackageCreate,
    getCrowdPackageDetail,
    crowdPackageEdit,
    crowdPackageGetCust,
    crowdPackageGetMobile,
    getCrowdPackageTemplate
} from '@/api/customer/crowdManage/index';
import { customerStatus, customerFrom } from '@/api/customer/clubManage/commonSea';
import { uploadFile2 } from '@/api/common';
import { useRouter, useRoute } from 'vue-router';

interface Props {
    id: any;
}

const router = useRouter();
const route = useRoute();
const backHandle = () => {
    router.back();
};
const formRef = ref<any>(null);
const uploadRef = ref<any>(null);
const batchLabelRef = ref<any>(null);

const rules = reactive<any>({
    name: [{ required: true, message: '请输入人群包名称', trigger: 'blur' }]
});

const formData = reactive<any>({
    isDisabled: route.query.type == 'look',
    isDisabled2: route.query.type == 'look' || route.query.type == 'edit',
    name: '',
    file_name: '',
    crowd_describe: '',
    crowd_set: 1,
    cust_screen: {
        is_have_mobile: 1,
        cust_stage: '',
        cust_source: '',
        tag_type: 3,
        exclude_tag_type: 3
    },
    tagType: '1',
    tagList: [],
    noTagList: [],
    custSourceList: [],
    custStageList: [],
    validMobileCount: 0,
    validCustCount: 0,
    is_lock: true
});

const tag_info = computed(() => {
    return formData.tagList.map((el: any) => el.id);
});

const exclude_tag_info = computed(() => {
    return formData.noTagList.map((el: any) => el.id);
});

const changeRadio = () => {
    if (formData.crowd_set == 1) {
        formData.is_lock = true;
    }
};

const props = withDefaults(defineProps<Props>(), {
    id: ''
});

const tagOptions = reactive([
    { label: '包含以下所有标签', code: 2 },
    { label: '包含以下任意标签', code: 1 },
    { label: '不限制', code: 3 }
]);

const tagList = reactive<any>([{ name: '123' }]);

const fileInfo = reactive({
    type: 5,
    label: '',
    prop: 'files',
    uploadFileList: formData.files,
    multiple: false,
    limitSize: 20,
    acceptFile: '.xls,.xlsx',
    uploadName: '上传模板'
});

const fileList = reactive([]);

const options = reactive([]);

const getFile = () => {};

const onHandleChange = async (file: UploadFile) => {
    formData.file_name = file.name;
    const params = {
        file: file.raw,
        fileName: file.name
    };
    const res = await uploadFile2(params);
    formData.file = res.url;
    handlerRecalculate();
};

const onRemoveUpload = () => {};

const handlerDownloadTemp = async () => {
    if (formData.isDisabled || formData.isDisabled2) return;
    const res = await getCrowdPackageTemplate();
    const a = document.createElement('a');
    a.href = res.url;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
};

const visibleChangeCustStage = async () => {
    if (!formData.custStageList.length) {
        const params = {
            page: 1,
            page_size: 99999
        };
        const res = await customerStatus(params);
        formData.custStageList = res || [];
    }
};

const visibleChangeCust = async () => {
    if (!formData.custSourceList.length) {
        const params = {
            page: 1,
            page_size: 99999
        };
        const res = await customerFrom(params);
        formData.custSourceList = res.data || [];
    }
};

const getTagsFun = (val: any) => {
    if (formData.tagType == '1') {
        formData.tagList = [...val.data] || [];
    } else {
        formData.noTagList = [...val.data] || [];
    }
};

const handlerTag = (type: string) => {
    formData.tagType = type;
    batchLabelRef.value.hasConditiion = false;
    batchLabelRef.value.dialogData.labelChooseType = 2;
    if (type == '1') {
        batchLabelRef.value.chooseDataArr = [...formData.tagList];
    } else if (type == '2') {
        batchLabelRef.value.chooseDataArr = [...formData.noTagList];
    }
    batchLabelRef.value.dialogVisible = true;
};

const closeTag = (index: number, type: string) => {
    if (type == '1') {
        formData.tagList.splice(index, 1);
    } else if (type == '2') {
        formData.noTagList.splice(index, 1);
    }
};

//
const checked = () => {
    if (formData.crowd_set == 2) {
        if ([1, 2].includes(formData.cust_screen.tag_type) && !tag_info.value.length) {
            ElMessage.error('标签至少选择一项！');
            return false;
        } else if ([1, 2].includes(formData.cust_screen.exclude_tag_type) && !exclude_tag_info.value.length) {
            ElMessage.error('排除标签至少选择一项！');
            return false;
        }
        return true;
    } else {
        return true;
    }
};

// 重新计算数量
const handlerRecalculate = async () => {
    if (formData.isDisabled) return;
    if (formData.crowd_set == 1) {
        const params = {
            file: formData.file
        };
        const res = await crowdPackageGetMobile(params);
        formData.validMobileCount = res.valid_mobile_count || 0;
    } else if (formData.crowd_set == 2) {
        const params = {
            is_have_mobile: formData.cust_screen.is_have_mobile,
            cust_stage: formData.cust_screen.cust_stage,
            cust_source: formData.cust_screen.cust_source,
            tag_type: formData.cust_screen.tag_type,
            exclude_tag_type: formData.cust_screen.exclude_tag_type,
            tag_info: tag_info.value,
            exclude_tag_info: exclude_tag_info.value
        };
        const res = await crowdPackageGetCust(params);
        formData.validCustCount = res.valid_mobile_count || 0;
    }
};

// 详情
const initDetail = async () => {
    const params = {
        id: route.query.id
    };
    const res = await getCrowdPackageDetail(params);
    visibleChangeCustStage();
    visibleChangeCust();
    const obj = res || {};
    Object.assign(formData, obj);
    if (obj.crowd_set == 2) {
        formData.cust_screen.is_have_mobile = obj.filter_condition.is_have_mobile;
        formData.cust_screen.tag_type = obj.filter_condition.tag_type;
        formData.cust_screen.exclude_tag_type = obj.filter_condition.exclude_tag_type;
        formData.cust_screen.cust_stage = obj.filter_condition.cust_stage;
        formData.cust_screen.cust_source = obj.filter_condition.cust_source;
        formData.tagList = obj.filter_condition.tag_info_list || [];
        formData.noTagList = obj.filter_condition.exclude_tag_info_list || [];
    }
    formData.validMobileCount = obj.valid_mobile_qty;
    formData.validCustCount = obj.valid_mobile_qty;
    formData.is_lock = obj.is_lock == 1 ? false : true;
};

// 保存-新建/编辑
const onSubmit = async () => {
    formRef.value.validate((res: any) => {
        if (res) {
            if (!checked()) {
                return;
            }
            const {
                name,
                file_name,
                crowd_set,
                file,
                crowd_describe,
                is_lock,
                cust_screen: { is_have_mobile, cust_stage, cust_source, tag_type, exclude_tag_type }
            } = formData;
            const cust_screen = {
                is_have_mobile,
                cust_stage,
                cust_source,
                tag_type,
                exclude_tag_type,
                tag_info_list: tag_type != 3 ? formData.tagList : [],
                exclude_tag_info_list: exclude_tag_type != 3 ? formData.noTagList : [],
                tag_info: tag_type != 3 ? tag_info.value : [],
                exclude_tag_info: exclude_tag_type != 3 ? exclude_tag_info.value : []
            };
            const params = {
                name,
                crowd_set,
                file,
                file_name,
                cust_screen,
                crowd_describe,
                is_lock
            };
            params.is_lock = params.is_lock ? 2 : 1;
            if (route.query.id) {
                params.crowd_package_id = route.query.id;
                detailEdit(params);
            } else {
                detailCreated(params);
            }
        }
    });
};

// 新建
const detailCreated = async (params: object) => {
    const res = await crowdPackageCreate(params);
    ElMessage.success('人群包创建成功！');
    router.back();
};

// 编辑
const detailEdit = async (params: object) => {
    const res = await crowdPackageEdit(params);
    ElMessage.success('人群包编辑成功！');
    router.back();
};

onMounted(() => {
    if (route.query.id) {
        initDetail();
    }
});
</script>
<style lang="scss" scoped>
.crowd-manage-detail-main {
    padding: 24px;

    .content {
        width: 800px;

        .mobile-upload {
            .mobile-upload-title {
                padding: 6px 8px;
                background: #fffaf9;

                span {
                    padding-left: 10px;
                    color: #ff6b00;
                    cursor: pointer;
                }
            }

            :deep(.el-upload) {
                width: 100%;
            }

            :deep(.el-upload-dragger) {
                margin: 24px 0;
                width: 100%;
                height: 240px;

                .file-box {
                    .file_img {
                        margin-top: 25px;
                        width: 50px;
                        height: 50px;
                    }

                    .file_name {
                        line-height: 24px;
                    }
                }
            }

            .upload-box {
            }
        }

        .screen-box {
            .screen-form-item {
                margin-bottom: 8px;
            }

            .screen-form-item-btn {
                margin-left: 12px;
            }
        }

        .screen-desc {
            span {
                color: #ff6b00;
            }

            .recalculate {
                padding-left: 10px;
                cursor: pointer;
            }
        }
    }
}

.text_box {
    margin-left: 120px;
    font-weight: 400;
    line-height: 20px;
    font-size: 14px;
    color: #33302d;
    padding: 16px;
    background: #fffaf9;
    border-radius: 4px;

    .box_tips {
        color: #ff6b00;
    }
}

.help_icon {
    vertical-align: middle;
    margin-left: 5px;
    cursor: pointer;
}
</style>
